const ArticleModel = require('../../model/ArticleModel')
const CategoryModel = require('../../model/CategoryModel')
const TagModel = require('../../model/TagModel')
const UserModel = require('../../model/UserModel')
const ArticleCommentModel = require('../../model/ArticleComment')

const dayjs = require('dayjs')

const articleService = {
   addArticle: async(data) => {
    const articleInfo = {
        ...data,
        viewNum: 0, // 阅读量
        createTime: Date.now(), // 创建时间
        updateTime: Date.now(), // 更新时间
        isDelete: false, // 是否删除
        likeNum: 0, // 点赞数
        commentNum: 0, // 评论数
    }
    const article = await ArticleModel.create(articleInfo)
    return article
   },
   getArticleList: async(left,right,articleType,userID) => {
    let data  = []
    let total = 0
    if(articleType === 1) {
        const articleList = await ArticleModel.find({isDelete: false, authorID: userID}).skip(left).limit(right).sort( { createTime: -1 } ).lean()
        data = articleList.concat([])
        total = await ArticleModel.countDocuments({isDelete: false, authorID: userID})
    } else if(articleType === 2) {
        // 查询已发布的文章
        const articleList = await ArticleModel.find({isDelete: false, isPublish: true, authorID: userID}).skip(left).limit(right).sort( { createTime: -1 } ).lean()
        data = articleList.concat([])
        total = await ArticleModel.countDocuments({isDelete: false, isPublish: true, authorID: userID})
    } else if(articleType === 3) {
        // 查询未发布的文章
        const articleList = await ArticleModel.find({isDelete: false, isPublish: false, authorID: userID}).skip(left).limit(right).sort( { createTime: -1 } ).lean()
        data = articleList.concat([])
        total = await ArticleModel.countDocuments({isDelete: false, isPublish: false, authorID: userID})
    } else if(articleType === 4) {
        // 查询已删除的文章
        const articleList = await ArticleModel.find({isDelete: true, authorID: userID}).skip(left).limit(right).sort( { createTime: -1 } ).lean()
        data = articleList.concat([])
        total = await ArticleModel.countDocuments({isDelete: true, authorID: userID})
    }
    // 查询对应分类
    for(let i = 0;i < data.length;i++) {
        const item = data[i]
        const category = await CategoryModel.findById(item.categoryID).lean()
        const user = await UserModel.findById(item.authorID).lean()
        const tagID = item.tags[0].split(",")
        const tag = await TagModel.find({_id: {$in: tagID}}).lean()
        tag.forEach(tagItem => {
            tagItem.icon = process.env.SERVER_BASE_URL + tagItem.icon
        })
        item.aboutInfo = {
            category,
            user: user.nickname
        }
        item.tags = tag
        item.content = ""
        item.cover = process.env.SERVER_BASE_URL + item.cover
        if(i === data.length -1) {
            return {
                data,
                total
            }
        }
    }
    return {
        data,
        total: 0
    }
    
   },
   getArticleDetail: async(id) => {
    const article = await ArticleModel.findById(id).lean()
    const category = await CategoryModel.findById(article.categoryID).lean()
    const user = await UserModel.findById(article.authorID).lean()
    const tagID = article.tags[0].split(",")
    const tag = await TagModel.find({_id: {$in: tagID}}).lean()
    tag.forEach(tagItem => {
        tagItem.icon = process.env.SERVER_BASE_URL + tagItem.icon
    })
    article.tags = tag
    article.aboutInfo = {
        category,
        author: user.nickname,
        tags: tag
    }
    article.cover = process.env.SERVER_BASE_URL + article.cover
    return article
   },
   updateArticle: async(data) => {
    data.updateTime = Date.now()
    const article = await ArticleModel.findByIdAndUpdate(data._id, data)
    return article
   },
   delArticle: async(id) => {
    const article = await ArticleModel.findByIdAndUpdate(id, {isDelete: true})
    return article
   },
   changePublish: async(id,isPublish) =>  {
    const article = await ArticleModel.findByIdAndUpdate(id, {isPublish})
   },
   searchArticle: async(tagsID,categoryID,articleType,userID) => {
    let data = []
    if(articleType === 1) {
        const articleList = await ArticleModel.find({isDelete: false,  categoryID, authorID: userID}).lean()
        data = articleList.concat([])
    } else if(articleType === 2) {
        // 查询已发布的文章
        const articleList = await ArticleModel.find({isDelete: false, isPublish: true, categoryID, authorID: userID}).lean()
        data = articleList.concat([])
    } else if(articleType === 3) {
        // 查询未发布的文章
        const articleList = await ArticleModel.find({isDelete: false, isPublish: false, categoryID, authorID: userID}).lean()
        data = articleList.concat([])
    } else if (articleType === 4) {
        // 查询已删除的文章
        const articleList = await ArticleModel.find({isDelete: true, categoryID, authorID: userID}).lean()
        data = articleList.concat([])
    }
    
    
    for(let i = 0;i < data.length;i++) {
        const item = data[i]
        const category = await CategoryModel.findById(item.categoryID).lean()
        const user = await UserModel.findById(item.authorID).lean()
        const tagID = item.tags[0].split(",")
        const tag = await TagModel.find({_id: {$in: tagID}}).lean()
        tag.forEach(tagItem => {
            tagItem.icon = process.env.SERVER_BASE_URL + tagItem.icon
        })
        item.aboutInfo = {
            category,
            user: user.nickname
        }
        item.tags = tag
        item.content = ""
        item.cover = process.env.SERVER_BASE_URL + item.cover
        if(i === data.length -1) {
            return data
        }
    }
    return data
   },
   delArticleRecover: async(id) => {
    const article = await ArticleModel.findByIdAndUpdate(id, {isDelete: false})
    return article
   },
   delArticlePermanently: async(id) => {
    const article = await ArticleModel.findByIdAndDelete(id)
    return article
   },
   delArticleAll: async(ids) => {
    const article = await ArticleModel.deleteMany({_id: {$in: ids}})
    return article
   },
   statistics: async(userID) => {
        // 定义统计量对象
        const count = {
            articleNum: 0,
            articlePublishNum: 0,
            articleUnPublishNum: 0,
            articleDeleteNum: 0,
            weekData: {}
        }
        // 查询当前用户的文章总数
        count.articleNum = await ArticleModel.countDocuments({isDelete: false, authorID: userID})
        // 查询已发布的文章数
        count.articlePublishNum = await ArticleModel.countDocuments({isDelete: false, isPublish: true, authorID: userID})
        // 查询未发布的文章数
        count.articleUnPublishNum = await ArticleModel.countDocuments({isDelete: false, isPublish: false, authorID: userID})
        // 查询已删除的文章数
        count.articleDeleteNum = await ArticleModel.countDocuments({isDelete: true, authorID: userID})
        // 查询在上次发布时间一长周内发布的文章数
        const nowDate = new Date()
        const weekAgo = new Date()
        weekAgo.setDate(weekAgo.getDate() - 7)
        const data = await ArticleModel.find({
            authorID: userID,
            createTime: {
                $gt: weekAgo,
                $lt: nowDate
            }
        })
        for(let i of data) {
            const key = dayjs(i.createTime).format("YYYY/MM/DD")
            count.weekData[key] = 0
        }
        for(let i of data) {
            const key = dayjs(i.createTime).format("YYYY/MM/DD")
            count.weekData[key]++
        }
        return count
   },
   getRecommends: async(authorID) => {
        const data = await ArticleModel.find({isDelete: false, isPublish: true, isTop: true, authorID}).limit(10).sort( {createTime: -1} ).lean()
        for(let item of data) {
            item.cover = process.env.SERVER_BASE_URL + item.cover
            const category = await CategoryModel.findById(item.categoryID).lean()
            const user = await UserModel.findById(item.authorID).lean()
            const tagID = item.tags[0].split(",")
            const tag = await TagModel.find({_id: {$in: tagID}}).lean()
            tag.forEach(tagItem => {
                tagItem.icon = process.env.SERVER_BASE_URL + tagItem.icon
            })
            item.aboutInfo = {
                category,
                user: {
                    name: user.nickname,
                    avatar: user.avatar,
                }
            }
            item.content = ""
            item.tags = tag
        }
        return data
   },
   getList: async(left,right,authorID) => {
    const data = await ArticleModel.find({isDelete: false ,isPublish: true, authorID}).limit(right).skip(left).sort( {createTime: -1} ).lean()
    const total = await ArticleModel.countDocuments({isDelete: false, isPublish: true, authorID})
        for(let item of data) {
            item.cover = process.env.SERVER_BASE_URL + item.cover
            const category = await CategoryModel.findById(item.categoryID).lean()
            const user = await UserModel.findById(item.authorID).lean()
            const tagID = item.tags[0].split(",")
            const tag = await TagModel.find({_id: {$in: tagID}}).lean()
            tag.forEach(tagItem => {
                tagItem.icon = process.env.SERVER_BASE_URL + tagItem.icon
            })
            item.aboutInfo = {
                category,
                user: {
                    name: user.nickname,
                    avatar: user.avatar,
                }
            }
            item.content = ""
            item.tags = tag
        }
        return {
            data,
            total
        }
   },
   like: async(id) => {
    await ArticleModel.findByIdAndUpdate(id, {
        $inc: {likeNum: 1}
    })
   },
   getPrevAndNext: async(id,createTime,authorID) => {
    console.log(createTime);
    const prev = await ArticleModel.find({isDelete: false, isPublish: true, authorID }).where("createTime").lt(createTime).sort( {createTime: -1} ).limit(1).select("title")
    const next = await ArticleModel.find({isDelete: false, isPublish: true, authorID }).where("createTime").gt(createTime).sort( {createTime: 1} ).limit(1).select("title")
    return {
        prev,
        next
    }
   },
   addView: async(id) => {
    await ArticleModel.findByIdAndUpdate(id, {
        $inc: {viewNum: 1}
    })
   },
   addComment: async(data) => {
    // 增加评论数
    await ArticleModel.findByIdAndUpdate(data.articleID, {
        $inc: {commentNum: 1}
    })
    // 获取文章信息，获取文章作者ID
    const article = await ArticleModel.findById(data.articleID)
    await ArticleCommentModel.create({
        ...data,
        createTime: new Date(),
        userID: article.authorID // 评论归属到文章作者
    })
   },
   getCommentList: async(id,left,right ) => {

    const data = await ArticleCommentModel.find({articleID: id}).sort("-time").skip(left).limit(right)
    const total = await ArticleCommentModel.countDocuments({articleID: id})
    return {
        data,
        total
    }
   },
   search: async(keyword,authorID) => {
        const data = await ArticleModel.find({isDelete: false, isPublish: true, authorID}).where("title").regex(keyword).sort( {createTime: -1} ).lean()
        for(let item of data) {
            item.cover = process.env.SERVER_BASE_URL + item.cover
            const category = await CategoryModel.findById(item.categoryID).lean()
            item.aboutInfo = category
        }
        return data
   }
}

module.exports = articleService;